package org.aliwo.ticket;

/**
 * @author xuyayuan
 * @data 2021年06月12日
 * 通过多线程，模拟三个窗口卖100张票的问题
 */
public class TicketThread {
    public static void main(String[] args) {

        //SaleTicketThread saleTicketThread1 = new SaleTicketThread();
        //SaleTicketThread saleTicketThread2 = new SaleTicketThread();
        //SaleTicketThread saleTicketThread3 = new SaleTicketThread();

        // 通过Thead类，会出现超卖的现象
        //saleTicketThread1.start(); // 启动售票线程
        //saleTicketThread2.start(); // 启动售票线程
        //saleTicketThread3.start(); // 启动售票线程

        SaleTicketRunnable saleTicketRunnable = new SaleTicketRunnable();
        Thread thread1 = new Thread(saleTicketRunnable);
        Thread thread2 = new Thread(saleTicketRunnable);
        Thread thread3 = new Thread(saleTicketRunnable);
        // 通过实现Runnable接口，会出现超卖的现象
        thread1.start(); // 启动售票线程
        thread2.start(); // 启动售票线程
        thread3.start(); // 启动售票线程
    }
}

class SaleTicketThread extends Thread {
    private static int ticketNum = 100;

    @Override
    public void run() {
        while (true) {

            if (ticketNum <= 0 ) {
                System.out.println("售票结束 !!!");
                break;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口号 : " + Thread.currentThread().getName() + " 卖出了一张票  "
                    + " 剩余票数 : " + (--ticketNum));
        }
    }
}


class SaleTicketRunnable implements Runnable {
    private  int ticketNum = 100;
    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0 ) {
                System.out.println("售票结束 !!!");
                break;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口号 : " + Thread.currentThread().getName() + "卖出了一张票  "
                    + " 剩余票数 : " + (--ticketNum));
        }
    }
}
